import os
import requests
import random
import time
import json
from datetime import datetime
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 定义目标Ajax接口信息
AJAX_API_URL = "https://crplingxi.com.cn/"  # 替换为实际的Ajax接口URL
# AJAX_API_URL = "https://nginx-uat.crplingxi.com.cn"  # 替换为实际的Ajax接口URL
HEADERS = {
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
    'Cookie': 'SESSION=1f2d4254-ceca-4945-a888-e13c9c240fdc; Hm_lvt_71070c2f506d8f1fe72a10f1ee410006=1713926208,1714009111,1714275649,1714354635; JSESSIONID=V1RqQo1DepOhS_TA9K9J9tW4ktHqd2tzjlCN0UaB; Hm_lpvt_71070c2f506d8f1fe72a10f1ee410006=1714357507',
}
FORM_HEADERS ={
    'Content-Type': 'multipart/form-data',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
    'Cookie': 'SESSION=1f2d4254-ceca-4945-a888-e13c9c240fdc; Hm_lvt_71070c2f506d8f1fe72a10f1ee410006=1713926208,1714009111,1714275649,1714354635; JSESSIONID=V1RqQo1DepOhS_TA9K9J9tW4ktHqd2tzjlCN0UaB; Hm_lpvt_71070c2f506d8f1fe72a10f1ee410006=1714357507',
}

def init_from_data():
    projectData = {
            'uids': get_sn(),
            'scene': '',
            'project_name': '',
            'project_address': '',
            'company_name': '',
            'project_price': '',
            'project_time': '',
            'project_text': '',
            'project_detail': '',
            'user_name': '测试用户1',
            'img_url': [],
            'project_file': [],
            'type_state': 2,
            'project_count': 0
        }
    return projectData

def get_sn():
    now = datetime.now()
    s = (
        str(now.year) +
        str(now.month).zfill(2) +
        str(now.day).zfill(2) +
        str(now.hour).zfill(2) +
        str(now.minute).zfill(2) +
        str(now.second).zfill(2) +
        str(now.microsecond // 1000).zfill(3) +
        str(int(random.random() * 1000)).zfill(3)
    )
    return s

def is_file_size_over_10MB(file_path):
    """
    检查指定文件的大小是否超过10MB。

    参数:
        file_path (str): 文件的完整路径。

    返回:
        bool: 如果文件大小超过10MB，则返回True；否则返回False。
    """
    file_size = os.path.getsize(file_path)
    return file_size > 10485760

def upload_file(file_path,filename,projectData):
    """上传单个文件到Ajax接口"""

    # 构建文件数据，这里假设接口接受名为`file`的表单项
    formData = {
        'businessType':'projectText',
        'businessId': projectData['uids']
    }
    files = {
        'file': (filename, open(file_path, "rb"),'application/pdf'),
    }
    try:
        response = requests.post(AJAX_API_URL+ '/oss/filemag/upload', data=formData, files=files, headers=HEADERS, verify=False)
        response.raise_for_status()  # 如果响应状态不是2xx，抛出HTTPError异常
        result = json.loads(response.text)
        if result['state'] == "1":
            file_id = result['id']
            print(f"[成功] 成功上传文件 {filename}，响应内容: id:{file_id}")
            datamsg = {
                'uid': get_sn(),
                'name': filename,
                'url': '/oss/filemag/getFileById?fileId=' + file_id
            }
            projectData['project_file'].append(datamsg)
            projectData['img_url'] = projectData['project_file']

            # 提交数据
            submit_data(projectData)
        else:
            print(f"[失败] 上传文件失败, msg: {result['msg']} ")
    except requests.exceptions.RequestException as e:
        print(f"[失败] 上传文件 {file_path} 失败，错误信息: {e}")
    finally:
        files["file"][1].close()  # 关闭文件

def submit_data(projectData):
    """提交表格数据接口"""
    # 构建文件数据
    datamsg = {
        'datamsg': json.dumps(projectData)
    }
    
    try:
        response = requests.post(AJAX_API_URL+ '/api/pbmag/dataManage/arithmeticSufferLib/control/addProjectText.do', data=datamsg, headers=HEADERS, verify=False)
        response.raise_for_status()  # 如果响应状态不是2xx，抛出HTTPError异常
        print(f"[成功] 成功提交项目 {projectData['project_name']}，响应内容: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"[失败] 提交项目 {projectData['project_name']} 失败，错误信息: {e}")

def upload_files_in_folder(folder_path):
    """读取指定文件夹下所有文件并逐个上传"""
    if not os.path.isdir(folder_path):
        raise NotADirectoryError(f"{folder_path}不是一个有效的目录")

    for root, _, filenames in os.walk(folder_path):
        for filename in filenames:
            file_path = os.path.join(root, filename)
            if is_file_size_over_10MB(file_path):
                print(f"文件 {filename} 大小超过10MB，跳过。")
            else:
                projectData = init_from_data()
                base_name, file_ext = os.path.splitext(filename)
                projectData['project_name'] = base_name
                projectData['project_text'] = base_name
                projectData['project_address'] = '-'

                projectData['business_type'] = '99'
                projectData['project_date'] = '2021'
                upload_file(file_path,filename, projectData) 
                time.sleep(2)

if __name__ == "__main__":
    # login_sys()
    target_folder = r"C:\Users\jacki\Downloads\tempDir\A案例合集\合同能源管理项目案例集（2021-2022）"
    upload_files_in_folder(target_folder)
    print(f"[成功] 导入项目完成。")